import React, { useState, useRef, useMemo, useEffect } from 'react';
import {
    Dialog,
    NavBar,
    Form,
    Input,
    Button,
    Picker,
    Radio,
    Toast
} from 'antd-mobile';

import { createArticleAPI, getArticleById, updateArticleAPI,delArticleAPI } from '@/apis/article'
import { useChannel } from '@/hooks/useChannel'
import { Link, useSearchParams, useLocation, useParams } from 'react-router-dom'
import { useUserContext } from '@/context/UserContext';

import { LimitCount } from '@/components/LimitCount';
import ReactQuill from 'react-quill';
import 'react-quill/dist/quill.snow.css';
import { v4 as uuidv4 } from 'uuid';


export default () => {

    const location = useLocation();
    const { pathname } = location;
    const { recordRouteName } = useUserContext();
    useEffect(() => {
        // console.log('getRouteName', getRouteName());
        recordRouteName(pathname);
    }, []);

    // 获取频道列表
    const { channelList } = useChannel()
    // 将 channels 数据转换为 Picker 所需的格式
    const pickerData = useMemo(() => {
        return (channelList || []).map(channel => ({
            label: channel.name,
            value: channel.id,
        }));
    }, [channelList]); // 只有当 channelList 变化时才会重新计算
    const pickerMap = [pickerData]
    const [visible, setVisible] = useState(false)
    const [value, setValue] = useState('');
    // 切换图片封面类型
    const [imageType, setImageType] = useState(0)
    // 新增状态管理
    const [fileList, setFileList] = useState([]);
    //提交按钮
    const [loading, setLoading] = useState(false);
    //删除按钮
    const [deleting, setDeleting] = useState(false);

    const quillRef = useRef(null);

    // 获取实例
    const [form] = Form.useForm()

    // 回填数据
    const { id } = useParams();

    const articleId = id;
    // console.log('searchParams', articleId)

    const onTypeChange = (e) => {
        console.log('切换封面了', e)
        setImageType(e)
        // console.log('imageType', imageType)
    }

    useEffect(() => {
        // 1. 通过id获取数据
        async function getArticleDetail() {
            const res = await getArticleById(articleId)
            const data = res.data
            const { cover, channel_id } = data
            form.setFieldsValue({
                ...data,
                type: cover.type
            })

            //显示频道
            setValue([channel_id])
            //显示图片类型
            setImageType(cover.type)
            // 显示图片({url:url})
            setFileList(cover.images.map(url => {
                return {
                    uid: uuidv4(),
                    name: '',
                    status: 'done',
                    url: url, // 使用接口返回的图片 URL
                }
            }))
        }
        // 只有有id的时候才能调用此函数回填
        if (articleId) {
            getArticleDetail()
        }
        // 2. 调用实例方法 完成回填
    }, [articleId, form])

    // 提交表单
    const onFinish = async (formValue) => {

        console.log(formValue)
        // 校验封面类型imageType是否和实际的图片列表imageList数量是相等的
        if (fileList.length !== imageType) return Toast.show('封面类型和图片数量不匹配')
        const { title, content, channel_id } = formValue
        // 1. 按照接口文档的格式处理收集到的表单数据
        const reqData = {
            title,
            content,
            cover: {
                type: imageType, // 封面模式
                images: fileList.map(item => {
                    if (item.response) {
                        return item.response.data.url
                    } else {
                        return item.url
                    }
                }) // 图片列表
            },
            channel_id
        }
        reqData.channel_id = value[0]
        console.log('reqData', reqData)

        setLoading(true);
        try {
            if (articleId) {
                // 更新接口
                updateArticleAPI({ ...reqData, id: articleId }).then(res => {
                    // console.log('更新接口',res)
                    if (res.message === 'OK') {
                        Toast.show('修改成功')
                        // console.log('提交成功')
                    }
                    setLoading(false);
                    setTimeout(() => {
                        back();
                    }, 1000);
                }).catch(err => {
                    console.log(err)
                })
            } else {
                createArticleAPI(reqData).then(res => {
                    // console.log('更新接口',res)
                    if (res.message === 'OK') {
                        Toast.show('提交成功')
                        // console.log('提交成功')
                    }
                    setLoading(false);
                }).catch(err => {
                    console.log(err)
                })
            }
        } catch (error) {
            setLoading(false);
            console.log(error)
        } finally {
        }

    }

    //回退
    const back = () => {
        history.go(-1)
    }

    return (
        <>
            <NavBar backIcon={true} onBack={back}>
                文章详情
            </NavBar>
            <Form
                layout="horizontal"
                form={form}
                onFinish={onFinish}
                footer={
                    <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                        <Button
                            style={{ width: '45%' }}
                            onClick={() => {
                                // 删除逻辑
                                console.log('删除操作');
                                Dialog.confirm({
                                    content: '是否删除该文章?',
                                    onConfirm: async () => { 
                                        await delArticleAPI(articleId).then(res => {
                                            if (res.message === 'OK') {
                                                Toast.show({
                                                    icon: 'success',
                                                    content: '删除成功',
                                                    position: 'center',
                                                })
                                                Dialog.clear();
                                                setTimeout(() => {
                                                    back();
                                                }, 1000);
                                            }
                                        })
                                        throw new Error()
                                    },
                                })
                            }}
                            block
                            color="danger"
                            size="large"
                        >
                            删除
                        </Button>
                        <Button
                            style={{ width: '45%' }}
                            loading={loading}
                            loadingText="提交中"
                            block
                            type="submit"
                            color="primary"
                            size="large"
                        >
                            提交
                        </Button>
                    </div>
                }
            >
                <Form.Item
                    name="title"
                    label="标题"
                    rules={[{ required: true, message: '请输入文章标题' }]}
                >
                    <Input placeholder="请输入文章标题" />
                </Form.Item>

                <Form.Item
                    required
                    // name="channel_id"
                    label='频道'
                    onClick={() => {
                        setVisible(true)
                    }}
                >
                    <Picker
                        columns={pickerMap}
                        visible={visible}
                        onClose={() => {
                            setVisible(false)
                        }}
                        value={value}
                        onConfirm={v => {
                            console.log(v)
                            setValue(v)
                        }}
                    >
                    </Picker>
                    <span>{channelList.find(item => item.id === value[0])?.name || '请选择'}</span>
                </Form.Item>

                <Form.Item label='封面' required>
                    <Radio.Group value={imageType} onChange={onTypeChange}>
                        <Radio value={1}>单图</Radio>
                        <Radio value={3}>三图</Radio>
                        <Radio value={0}>无图</Radio>
                    </Radio.Group>
                </Form.Item>

                {imageType != 0 &&
                    <LimitCount
                        maxCount={imageType}
                        onFileListChange={setFileList}
                        value={fileList}
                    />
                }

                <Form.Item
                    label="内容"
                    name="content"
                    rules={[{ required: true, message: '请输入文章内容' }]}
                >
                    {/* 富文本编辑器 */}
                    <ReactQuill
                        ref={quillRef}
                        className="publish-quill"
                        theme="snow"
                        placeholder="请输入文章内容"
                    />
                </Form.Item>


            </Form>
        </>
    );
};
